package org.wevil.util;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @author wanglei
 * @since 2021/10/13
 * */
public class MapUtil {
    /**
     * map转str
     *
     * @author wanglei
     * @since 2021/10/13
     * */
    public static String map2str(Map<String, String[]> map) {
        StringBuilder sb = new StringBuilder();
        if (!map.isEmpty()) {
            for (Map.Entry<String, String[]> entry : map.entrySet()) {
                String[] values = entry.getValue();
                StringBuilder vb = new StringBuilder();
                String value = "";
                if(values != null && values.length>0){
                    for(String s : values){
                        vb.append(s).append(",");
                    }
                    value = vb.substring(0, vb.length()-1);
                }
                sb.append(entry.getKey()).append("=").append(value).append("&");
            }
            return sb.substring(0, sb.length()-1);
        }
        else{
            return "";
        }
    }

    /**
     * 对象转map
     *
     * @author wanglei
     * @since 2021/6/25
     * */
    public static Map<String, String> obj2map(Object bean) {
        try {
            return org.apache.commons.beanutils.BeanUtils.describe(bean);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * map转对象
     *
     * @author wanglei
     * @since 2021/6/25
     * */
    public static void map2obj(Map<String, ?> map, Object obj){
        try {
            org.apache.commons.beanutils.BeanUtils.populate(obj, map);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
